#!/usr/bin/env python3

from question_classifier import *
from question_parser import *
from answer_search import *
from search_entity import create_json

'''
问答类：主入口，将 QuestionClassifier, QuestionParser, AnswerSearcher 串联起来 
'''


class ChatBotGraph:
    def __init__(self, g):
        # 意图识别 问题分类
        self.classifier = QuestionClassifier()
        # 构建问题 Cypher语句
        self.parser = QuestionParser()
        # 执行cypher查询，并按模版回复问题
        self.searcher = AnswerSearcher(g)

    def chat_main(self, sent):
        answer = '不好意思，该问题我还答不上来。日后我们将不断完善，祝您身体健康！'
        res_classify = self.classifier.classify(sent)
        if not res_classify:
            return answer
        print(res_classify)
        res_sql = self.parser.parser_main(res_classify)
        print(res_sql)
        final_answers, data = self.searcher.search_main(res_sql)
        new_data = []
        for item in data:
            if 'n' in item.keys() and 'r' in item.keys() and 'e' in item.keys():
                new_data.append(create_json(item['n'], item['r'], item['e']))
            else:
                new_data.append(create_json(item['n'], None, None))
        if not new_data:
            return {"answer": answer, 'data': []}
        else:
            # print(new_data)
            return {"answer": '\n'.join(final_answers), 'data': new_data}


if __name__ == '__main__':
    graph = Graph("http://localhost:7474", password="bigben123")
    handler = ChatBotGraph(graph)
    while 1:
        question = input('问题:')
        answer = handler.chat_main(question)
        print('回答:', answer)
